home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / pyshared / LanguageSelector / LocaleInfo.py < prev    next >
Encoding:
Python Source  |  2009-05-07  |  7.1 KB  |  193 lines

  1. # LoclaeInfo.py (c) 2006 Canonical, released under the GPL
  2. #
  3. # a helper class to get locale info
  4.  
  5. import string
  6. import re            
  7. import subprocess
  8. import gettext
  9. import os.path
  10.  
  11. from gettext import gettext as _
  12. from xml.etree.ElementTree import ElementTree
  13.  
  14. class LocaleInfo(object):
  15.     " class with handy functions to parse the locale information "
  16.     
  17.     environments = ["/etc/default/locale", "/etc/environment"]
  18.     def __init__(self, languagelist_file):
  19.         # map language to human readable name, e.g.:
  20.         # "pt"->"Portuguise", "de"->"German", "en"->"English"
  21.         self._lang = {}
  22.  
  23.         # map country to human readable name, e.g.:
  24.         # "BR"->"Brasil", "DE"->"Germany", "US"->"United States"
  25.         self._country = {}
  26.         
  27.         # map locale (language+country) to the LANGUAGE environment, e.g.:
  28.         # "pt_PT"->"pt_PT:pt:pt_BR:en_GB:en"
  29.         self._languagelist = {}
  30.         
  31.         # read lang file
  32.         et = ElementTree(file="/usr/share/xml/iso-codes/iso_639.xml")
  33.         it = et.getiterator('iso_639_entry')
  34.         for elm in it:
  35.             lang = elm.attrib["name"]
  36.             if elm.attrib.has_key("iso_639_1_code"):
  37.                 code = elm.attrib["iso_639_1_code"]
  38.             else:
  39.                 code = elm.attrib["iso_639_2T_code"]
  40.             self._lang[code] = lang
  41.         et = ElementTree(file="/usr/share/xml/iso-codes/iso_639_3.xml")
  42.         it = et.getiterator('iso_639_3_entry')
  43.         for elm in it:
  44.             lang = elm.attrib["name"]
  45.             code = elm.attrib["id"]
  46.             if not self._lang.has_key(code):
  47.                 self._lang[code] = lang
  48.             
  49.         # read countries
  50.         et = ElementTree(file="/usr/share/xml/iso-codes/iso_3166.xml")
  51.         it = et.getiterator('iso_3166_entry')
  52.         for elm in it:
  53.             if elm.attrib.has_key("common_name"):
  54.                 descr = elm.attrib["common_name"]
  55.             else:
  56.                 descr = elm.attrib["name"]
  57.             if elm.attrib.has_key("alpha_2_code"):
  58.                 code = elm.attrib["alpha_2_code"]
  59.             else:
  60.                 code = elm.attrib["alpha_3_code"]
  61.             self._country[code] = descr
  62.             
  63.         # read the languagelist
  64.         for line in open(languagelist_file):
  65.             tmp = line.strip()
  66.             if tmp.startswith("#") or tmp == "":
  67.                 continue
  68.             w = tmp.split(";")
  69.             # FIXME: the latest localechoosers "languagelist" does
  70.             # no longer have this field for most languages, so
  71.             # deal with it and don't set LANGUAGE then
  72.             # - the interessting question is what to do
  73.             # if LANGUAGE is already set and the new
  74.             localeenv = w[6].split(":")
  75.             #print localeenv
  76.             self._languagelist[localeenv[0]] = '%s' % w[6]
  77.  
  78.     def lang(self, code):
  79.         """ map language code to language name """
  80.         if self._lang.has_key(code):
  81.             return self._lang[code]
  82.         return ""
  83.  
  84.     def country(self, code):
  85.         """ map country code to country name"""
  86.         if self._country.has_key(code):
  87.             return self._country[code]
  88.         return ""
  89.  
  90.     def generated_locales(self):
  91.         """ return a list of locales available on the system
  92.             (running locale -a) """
  93.         locales = []
  94.         p = subprocess.Popen(["locale", "-a"], stdout=subprocess.PIPE)
  95.         for line in string.split(p.communicate()[0], "\n"):
  96.             tmp = line.strip()
  97.             if tmp.startswith("#") or tmp == "" or tmp == "C" or tmp == "POSIX":
  98.                 continue
  99.             # we are only interessted in the locale, not the codec
  100.             locale = string.split(tmp)[0]
  101.             locale = string.split(locale,".")[0]
  102.             locale = string.split(locale,"@")[0]
  103.             if not locale in locales:
  104.                 locales.append(locale)
  105.         #print locales
  106.         return locales
  107.  
  108.     def translate_language(self, lang):
  109.         "return translated language"
  110.         lang_name = gettext.dgettext('iso_639', self._lang[lang])
  111.         if lang_name == self._lang[lang]:
  112.             lang_name = gettext.dgettext('iso_639_3', self._lang[lang])
  113.         return lang_name
  114.  
  115.     def translate_locale(self, locale):
  116.         """
  117.         return translated language and country of the given
  118.         locale into the given locale, e.g. 
  119.         (Deutsch, Deutschland) for de_DE
  120.         """
  121.         (lang, country) = string.split(locale, "_")
  122.         current_language = None
  123.         if "LANGUAGE" in os.environ:
  124.             current_language = os.environ["LANGUAGE"]
  125.         os.environ["LANGUAGE"]=locale
  126.         lang_name = self.translate_language(lang)
  127.         country_name = gettext.dgettext('iso_3166', self._country[country])
  128.         if current_language:
  129.             os.environ["LANGUAGE"] = current_language
  130.         return (lang_name, country_name)
  131.  
  132.     def translate(self, locale):
  133.         """ get a locale code and output a human readable name """
  134.         if "_" in locale:
  135.             (lang, country) = string.split(locale, "_")
  136.             (lang_name, country_name) = self.translate_locale(locale)
  137.             # get all locales for this language
  138.             l = filter(lambda k: k.startswith(lang+"_"), self.generated_locales())
  139.             # only show region/country if we have more than one 
  140.             if len(l) > 1:
  141.                 mycountry = self.country(country)
  142.                 if mycountry:
  143.                     return "%s (%s)" % (lang_name, country_name)
  144.                 else:
  145.                     return lang_name
  146.             else:
  147.                 return lang_name
  148.         return self.translate_language(locale)
  149.  
  150.     def makeEnvString(self, code):
  151.         """ input is a language code, output a string that can be put in
  152.             the LANGUAGE enviroment variable.
  153.             E.g: en_DK -> en_DK:en
  154.         """
  155.         # first check if we got somethign from languagelist
  156.         if self._languagelist.has_key(code):
  157.             return self._languagelist[code]
  158.         # if not, fall back to "dumb" behaviour
  159.         if not "_" in code:
  160.             return code
  161.         (lang, region) = string.split(code, "_")
  162.         return "%s:%s" % (code, lang)
  163.  
  164.     def getDefaultLanguage(self):
  165.         """ returns the current default language (e.g. zh_CN) """
  166.         for environment in self.environments:
  167.             if not os.path.exists(environment):
  168.                 continue
  169.             for line in open(environment).readlines():
  170.                 line = line.strip()
  171.                 if line.startswith("LANGUAGE="):
  172.                     (key,value) = line.split("=")
  173.                     value = value.strip('"')
  174.                     return value.split(":")[0]
  175.             for line in open(environment).readlines():
  176.                 match = re.match(r'LANG="([a-zA-Z_]*).*"$',line)
  177.                 if match:
  178.                     return match.group(1)
  179.         return None
  180.  
  181. if __name__ == "__main__":
  182.     datadir = "/usr/share/language-selector/"
  183.     li = LocaleInfo("%s/data/languages" % datadir,
  184.                     "%s/data/countries" % datadir,
  185.                     "%s/data/languagelist" % datadir)
  186.  
  187.     print "default: '%s'" % li.getDefaultLanguage()
  188.  
  189.     print li._lang
  190.     print li._country
  191.     print li._languagelist
  192.     print li.generated_locales()
  193.